package com.goldcn.sys.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldcn.common.*;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.config.PropertiesConfig;
import com.goldcn.sys.dao.UserInfoMapper;
import com.goldcn.sys.model.UserInfo;
import com.goldcn.sys.model.UserLogin;
import com.goldcn.util.JsonUtil;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Li manNa
 * mail: lmn_022@163.com
 * Date: 2017/6/19
 * Time: 17:06
 * To change this template use File | Settings | File Templates.
 */
@Service
@Transactional
public class EmployeeService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    PropertiesConfig propertiesConfig;

    @Autowired
    RestTemplate restTemplate;

    public Map selectAll(Map<String,String> params) {

        String name = params.get("CNName");
        String mobile = params.get("mobile");

        int isStop = 100;
        String state = params.get("isStop");
        if(Strings.isNotBlank(state)){
            isStop = Integer.parseInt(state);
        }

        //分页
        int pageSize = Integer.parseInt(params.get("pageSize"));
        int pageIndex = Integer.parseInt(params.get("pageIndex"))*pageSize;

        String sortField = params.get("sortField");
        String sortOrder = params.get("sortOrder");
        String condition = "";

        if(CommonUtils.isNotEmpty(name)){
            condition = "and us.name like '%"+name+"%'";
        }
        if(CommonUtils.isNotEmpty(mobile)){
            condition += " and us.mobile like '%"+mobile+"%'";
        }
        if(isStop==0||isStop==1){
            condition += " and us.isStop= "+isStop;
        }

        int pageCount = userInfoMapper.selectAllNum(condition);
        List<Map<String,Object>>  userList = userInfoMapper.selectAll(pageIndex,pageSize,condition,sortField,sortOrder);
        for (Map<String,Object> map : userList){
            map.put("uid",String.valueOf(map.get("userID")));
        }

        HashMap result = new HashMap();
        result.put("data", userList);
        result.put("total", pageCount);

        return result;
    }

    public ResultData updatePassWord(Long userID) {
        ResultData resultData = new ResultData();

        UserInfo model = userInfoMapper.selectByPrimaryKey(userID);

        if (null == model) {
            resultData.setMessage("用户不存在！");
            resultData.setCode(BaseCode.ERROR_CODE);
            return resultData;
        }

        List<UserLogin> ulList = userInfoMapper.getLoginListByUserID(model.getUserID());
        for (UserLogin ul : ulList) {
            ul.setPassWord(propertiesConfig.getEmployeeInitPwd());
            userInfoMapper.updateUserLoginPwd(ul);
        }

        model.setPassWord(propertiesConfig.getEmployeeInitPwd());//888888 == 6个8

        int result = userInfoMapper.updateByPrimaryKeySelective(model);

        resultData.setCode(String.valueOf(result));
        return resultData;
    }

    public ResultData<Object> getEmployee(Long userId) {
        ResultData<Object> resultData = new ResultData<Object>();

        Map<String,Object> userInfoMap = new HashMap();
        Map<String,Object> userInfo =userInfoMapper.searchUserOrg(userId);

        userInfoMap.put("userInfo",userInfo);
        resultData.setData(userInfoMap);

        return resultData;
    }

    public ResultData<Object> deleteEmployee(Long userId) {
        ResultData result = new ResultData();
        Map<String,Object> orderMap = new HashMap();
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        if(null==userInfo){
            throw new ServiceException("员工信息不存在", RestConst.ErrorCode.DATABASE_ERROR);
        }

        //是否已下单
        orderMap.put("uid",userId);
        userInfoMapper.searchOrder(orderMap);
        if(null != orderMap.get("orderCount")&&Integer.valueOf(orderMap.get("orderCount").toString())>0){
            result.setCode("125");
            result.setMessage("该员工已有订单记录，不能删除！");
            return result;
        }

        orderMap.put("inCompanyID",userInfo.getCompanyID());
        userInfoMapper.isAdmin(orderMap);
        if(null != orderMap.get("res")&&Integer.valueOf(orderMap.get("res").toString())>0){
            result.setCode("127");
            result.setMessage("该员工为管理员，不能删除！");
            return result;
        }

        //删除用户信息;
        userInfoMapper.delEmployee(orderMap);
        return result;
    }


    public Map<String, Object> getPartnerListByUserId(Long userId, int pageNo, int pageSize) {
        Map para = new HashMap();
        para.put("userID", userId);

        Map<String, Object> result = new HashMap<String, Object>();
        PageHelper.startPage(pageNo, pageSize);
        List list = userInfoMapper.getPartnerListByUserId(para);
        PageInfo page = new PageInfo(list);

        result.put("data", page.getList());
        result.put("total", page.getTotal());

        return result;

    }

    public Map<String, Object> getOrderListByUserId(Long userId, int pageNo, int pageSize) {
        Map para = new HashMap();
        para.put("userID", userId);
        para.put("dbOrder", propertiesConfig.getDbOrder());

        Map<String, Object> result = new HashMap<String, Object>();
        PageHelper.startPage(pageNo, pageSize);
        List list = userInfoMapper.getOrderListByUserId(para);
        PageInfo page = new PageInfo(list);

        result.put("data", page.getList());
        result.put("total", page.getTotal());

        return result;

    }

    public Map selectAllOrderInfo(Map<String,String> params,int pageNo, int pageSize) {
        params.put("dbOrder", propertiesConfig.getDbOrder());

        Map<String, Object> result = new HashMap<String, Object>();
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String,Object>>  list = userInfoMapper.selectAllOrderInfo(params);
        for (Map map : list){
            map.put("orderID",String.valueOf(map.get("orderID")));
        }
        PageInfo page = new PageInfo(list);

        result.put("data", page.getList());
        result.put("total", page.getTotal());

        return result;
    }


    public ResultData<Object> getOrderInfoAndItem(Long orderId) {
        ResultData<Object> resultData = new ResultData<Object>();

        Map para = new HashMap();
        para.put("orderID", orderId);;
        para.put("dbOrder", propertiesConfig.getDbOrder());

        Map<String,Object> map = new HashMap();

        Map<String,String> info =userInfoMapper.getOrderInfoByOrderId(para);
        List list = userInfoMapper.getOrderItemByOrderId(para);

        map.put("info",info);
        map.put("item",list);
        resultData.setData(map);

        return resultData;
    }

    public ResultData delOrderInfo(Long orderId){
        List<Long> list = new ArrayList();
        list.add(orderId);
        JSONObject jsonObject = HttpUtil.httpPOSTJSONObject(propertiesConfig.getBankServiceURL()+"orderUtil/delete", list,restTemplate,true);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("订单索引出错", RestConst.ErrorCode.DATABASE_ERROR);
        }
        return new ResultData(jsonObject.get("isSuccess").toString(),jsonObject.get("data"));
    }

    public Map<String, Object> userPoint(Map<String, String> para,int pageNo, int pageSize) {
        para.put("dbPoint", propertiesConfig.getDbPoint());

        Map<String, Object> result = new HashMap<String, Object>();
        PageHelper.startPage(pageNo, pageSize);
        List list = userInfoMapper.getPointList(para);
        PageInfo page = new PageInfo(list);

        result.put("data", page.getList());
        result.put("total", page.getTotal());

        return result;

    }


    public Map getPointDetailsByUserId(String userID) {
        Map<String, String> para = new HashMap();
        para.put("dbPoint", propertiesConfig.getDbPoint());
        para.put("userID",userID);

        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String,Object>>  list = userInfoMapper.getPointDetailsByUserId(para);

        result.put("data", list);

        return result;
    }

    public Map getJOBList() {
        Map<String, String> para = new HashMap();
        para.put("dbJob", propertiesConfig.getDbJob());


        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String,Object>>  list = userInfoMapper.getJOBList(para);

        for (Map<String,Object> m : list){
            if(null !=m.get("JOB_DATA")){
                m.put("JOB_DATA",m.get("JOB_DATA").toString().substring(m.get("JOB_DATA").toString().indexOf("=")+1));
            }
        }
        result.put("data", list);

        return result;
    }

    public ResultData addJob(Map<String,String> param) {
        Integer opt = DataUtils.toInt(param.get("opt"));
        String job = param.get("job");
        Map<String,String> dataMap = JsonUtil.toMap(job);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("taskId",dataMap.get("taskId").trim());
        map.put("time", dataMap.get("time").trim());
        map.put("jobUrl", dataMap.get("jobUrl").trim());
        map.put("group", dataMap.get("group").trim());
        if(opt==1){
            deleteJob(param.get("oldTaskID").trim(),param.get("oldGroup").trim());
        }
        DataResult dataResult = restTemplate.postForObject(propertiesConfig.getCronjob(), map, DataResult.class);
        ResultData resultData = new ResultData();
        if (dataResult.getIsSuccess()== 0) {
            resultData.setCode("0");
            return  resultData;
        }
        return new ResultData();
    }

    public ResultData deleteJob(String taskID,String group){
        restTemplate.delete(propertiesConfig.getCronjob() + "/" + taskID + "/" + group);
        return new ResultData();
    }

    public ResultData delOrderByCompanyID(Long companyID){
        Map<String, Object> para = new HashMap();
        para.put("dbOrder", propertiesConfig.getDbOrder());
        para.put("companyID", companyID);
        List<Long>  list = userInfoMapper.getOrderIdsByCompanyID(para);
        /*ResultData resultData = restTemplate.postForObject(propertiesConfig.getBankServiceURL()+"orderUtil/delete", list, ResultData.class);
        return resultData;*/
        JSONObject jsonObject = HttpUtil.httpPOSTJSONObject(propertiesConfig.getBankServiceURL()+"orderUtil/delete", list,restTemplate,true);
        return new ResultData(jsonObject.get("isSuccess").toString(),jsonObject.get("data"));
    }

    public ResultData<Object> deleteGoodsByCompanyID(Long companyID) {
        Map<String,Object> goodsMap = new HashMap();

        goodsMap.put("companyID",companyID);

        userInfoMapper.delGoodsByCompanyID(goodsMap);

        /*ResultData resultData = restTemplate.postForObject(propertiesConfig.getBankServiceURL()+"goods/delAllGoods", companyID, ResultData.class);
        return resultData;*/
        //删除索引
        JSONObject jsonObject = HttpUtil.httpPOSTJSONObject(propertiesConfig.getBankServiceURL()+"goods/delAllGoods", companyID,restTemplate,true);
        return new ResultData(jsonObject.get("isSuccess").toString(),jsonObject.get("data"));
    }

    public Map selectAllGoods(Map<String,String> params,int pageNo, int pageSize) {
        params.put("dbOrder", propertiesConfig.getDbOrder());

        Map<String, Object> result = new HashMap<String, Object>();
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String,Object>>  list = userInfoMapper.selectAllGoods(params);
        for (Map map : list){
            map.put("goodsID",String.valueOf(map.get("goodsID")));
        }
        PageInfo page = new PageInfo(list);

        result.put("data", page.getList());
        result.put("total", page.getTotal());

        return result;
    }

    public ResultData<Object> deleteGoodsByGoodsID(Long goodsID) {
        Map<String,Object> goodsMap = new HashMap();

        goodsMap.put("goodsID",goodsID);
        userInfoMapper.delGoodsByGoodsID(goodsMap);
        /*ResultData resultData = restTemplate.postForObject(propertiesConfig.getBankServiceURL()+"goods/delGoodsByGoodsID", goodsID, ResultData.class);
        return resultData;*/
        //删除索引
        JSONObject jsonObject = HttpUtil.httpPOSTJSONObject(propertiesConfig.getBankServiceURL()+"goods/delGoodsByGoodsID", goodsID,restTemplate,true);
        return new ResultData(jsonObject.get("isSuccess").toString(),jsonObject.get("data"));
    }

    public ResultData<Object> delAllUserInfo(Long companyID) {
        Map<String,Object> orderMap = new HashMap();
        List<Long> userIds = userInfoMapper.selectAllFilterSuperAdmin(companyID);
        for (Long userId : userIds){
            orderMap.put("uid",userId);
            //删除用户信息;
            userInfoMapper.delEmployee(orderMap);
        }
        return new ResultData();
        /*

        //删除ES
        *//*ResultData resultData = restTemplate.postForObject(propertiesConfig.getBankServiceURL()+"orderUtil/delete", userIds, ResultData.class);
        return resultData;*//*
        *//*List<String>
        JSONObject jsonObject = HttpUtil.httpPOSTJSONObject(propertiesConfig.getBankServiceURL()+"orderUtil/delete", list,restTemplate,true);
        return new ResultData(jsonObject.get("isSuccess").toString(),jsonObject.get("data"));*//*
        //删除订单索引
        return delOrderByCompanyID(companyID);*/
    }


    public ResultData<Object> delOrg(Long companyID){
        int i =  userInfoMapper.delOrganizational(companyID);
        return new ResultData();
    }

}
